<?php
require_once('BaseDAO.php');

class DatabaseDAO extends BaseDAO
{
    const USER_DATABASE = "user_database";

    public function getUserDatabases($userId)
    {
        $userDatabase = self::USER_DATABASE;
        return $this->executeQuery("SELECT * FROM $userDatabase WHERE UserId = '$userId'");
    }

    public function getDatabasesTables($databaseId)
    {
        $connection = $this->getDatabaseConnection($databaseId);
        $tableNames = $this->executeQueryWithConnection($connection, "SHOW TABLES");
        $tableNamesArray = array();
        while ($row = mysqli_fetch_array($tableNames)) {
            $tableNamesArray[] = $row[0];
        }
        mysqli_close($connection);
        return $tableNamesArray;
    }

    public function saveDatabase($database)
    {
        $this->addItem(self::USER_DATABASE, $database);
    }

    public function updateDatabase($database, $itemId)
    {
        $this->updateItem(self::USER_DATABASE, $database, $itemId);
    }

    public function deleteDatabase($databaseId)
    {
        $this->deleteItem(self::USER_DATABASE, $databaseId);
    }

    public function getTableColumns($databaseId, $tableName)
    {
        $connection = $this->getDatabaseConnection($databaseId);
        $columns = $this->executeQueryWithConnection($connection, "SHOW COLUMNS FROM $tableName");
        $columnNamesArray = array();
        while ($row = mysqli_fetch_array($columns)) {
            $columnNamesArray[] = $row[0];
        }
        mysqli_close($connection);
        return $columnNamesArray;
    }

    /**
     * @param $databaseId
     * @return mysqli
     */
    protected function getDatabaseConnection($databaseId)
    {
        $database = $this->getDatabase($databaseId);
        $connection = mysqli_connect($database["URL"], $database["User"], $database["Password"], $database["DatabaseName"]);
        // Check connection
        if (mysqli_connect_errno()) {
            die("Failed to connect to MySQL: " . mysqli_connect_error());
        }
        return $connection;
    }

    public function getDatabase($databaseId)
    {
        return mysqli_fetch_assoc($this->getItem(self::USER_DATABASE, $databaseId));
    }

    public function checkConnection($database)
    {
        mysqli_connect($database["URL"], $database["User"], $database["Password"], $database["DatabaseName"]);
        if (mysqli_connect_errno()) {
            return false;
        }
        return true;
    }
}
?>